/**
 * 
 */
package com.jdy.haoduoaiteacher.adapter;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jdy.haoduoaiteacher.Constant;
import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.enums.PosterType;
import com.jdy.haoduoaiteacher.event.OnMediaResendEvent;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.MemberType;
import com.jdy.haoduoaiteacher.util.CircleTransform;
import com.jdy.haoduoaiteacher.util.CommonUtil;
import com.jdy.haoduoaiteacher.util.DateUtils;
import com.jdy.haoduoaiteacher.util.Tools;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class SpeakWordHistoryAdapter extends BaseAdapter {
  private final Activity mContext;
  private  List<SpeakForYouItem> wordList;
  private final LayoutInflater mInflater;
  private final SparseArray<View> mSArray;
  private final Uri BabyUri;
  private  Uri ParentUri;
  private LeUser mLeUser;
  private String headIcon;

  public void udpateImagePath() {
    SharedPreferences prefs = this.mContext.getSharedPreferences(
            Constant.USER_INFO, Context.MODE_PRIVATE);
    String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");
    this.ParentUri = Uri.parse(parentImagePath);
    mLeUser = MyTeacherApp.getInstance().getUserTeacher();
    if (mLeUser != null && mLeUser.member_types!=null && !mLeUser.member_types.isEmpty()) {
      for (MemberType item : mLeUser.member_types) {
        if (item.type_id ==1) {
          headIcon = item.avatar;
          break;
        }
      }
    }
  }

  public void updateData (List<SpeakForYouItem> wordLisst) {
    wordList = wordLisst;
   //   notifyDataSetChanged();
  }

  VoicePlayClickListener.VoiceClickListener mVoiceClickListener;

  public SpeakWordHistoryAdapter(Activity context,
      List<SpeakForYouItem> wordList, VoicePlayClickListener.VoiceClickListener li) {
    mVoiceClickListener = li;
    this.mContext = context;
    this.wordList = wordList;
    this.mInflater = LayoutInflater.from(mContext);
    mSArray = new SparseArray<View>();
    mLeUser = MyTeacherApp.getInstance().getUserTeacher();
    SharedPreferences prefs = this.mContext.getSharedPreferences(
        Constant.USER_INFO, Context.MODE_PRIVATE);
    String babyImagePath = prefs.getString(Constant.BABY_AVATAR, "");
    this.BabyUri = Uri.parse(babyImagePath);
    String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");
    this.ParentUri = Uri.parse(parentImagePath);

    if (mLeUser != null && mLeUser.member_types!=null && !mLeUser.member_types.isEmpty()) {
      for (MemberType item : mLeUser.member_types) {
        if (item.type_id ==1) {
          headIcon = item.avatar;
          break;
        }
      }
    }
  }

  @Override
  public int getCount() {
    return wordList.size();
  }

  @Override
  public Object getItem(int position) {
    return wordList.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    convertView = mSArray.get(position);
    final SpeakForYouItem sfyi = wordList.get(position);

    holder = new ViewHolder();
    if (convertView == null) {
      switch (sfyi.SFYType) {
      case TEXT:
        if (sfyi.posterType.equals(PosterType.Turing)) {
          convertView = mInflater.inflate(
              R.layout.turing_speak_history_list_item, null);
        } else {
          convertView = mInflater.inflate(R.layout.speak_history_list_item_teacher,
              null);
          holder.speakLayout = (com.jdy.haoduoaiteacher.view.SquareLayout) convertView
              .findViewById(R.id.speak_slayout);
          holder.timestampTv = (TextView) convertView
                  .findViewById(R.id.timestamp);
          holder.avatarImg = (ImageView) convertView
                  .findViewById(R.id.avatar_img);
          holder.contentTV = (TextView) convertView.findViewById(R.id.record_tv);
          holder.coverImg = (ImageView) convertView.findViewById(R.id.story_img);
          holder.errorIconImg = (ImageView) convertView
                  .findViewById(R.id.send_error_img);
          holder.pBar = (ProgressBar) convertView
                  .findViewById(R.id.sending_progressbar);
        }

        break;
      case VIDEO:
        convertView = mInflater.inflate(R.layout.speak_history_list_item_teacher, null);
        holder.timestampTv = (TextView) convertView
            .findViewById(R.id.timestamp);
        holder.speakLayout = (com.jdy.haoduoaiteacher.view.SquareLayout) convertView
            .findViewById(R.id.speak_slayout);
        holder.avatarImg = (ImageView) convertView
            .findViewById(R.id.avatar_img);
        holder.contentTV = (TextView) convertView.findViewById(R.id.record_tv);
        holder.coverImg = (ImageView) convertView.findViewById(R.id.story_img);
        holder.errorIconImg = (ImageView) convertView
            .findViewById(R.id.send_error_img);
        holder.pBar = (ProgressBar) convertView
            .findViewById(R.id.sending_progressbar);
        break;
      case VOICE:
          if (sfyi.posterType == PosterType.Parent) {
              convertView = mInflater.inflate(R.layout.row_sent_voice, null);
              holder.timestampTv = (TextView) convertView
                      .findViewById(R.id.timestamp);
              holder.avatarImg = (ImageView) convertView
                      .findViewById(R.id.iv_userhead);
              holder.coverImg = (ImageView) convertView.findViewById(R.id.iv_voice);
              holder.pBar = (ProgressBar) convertView.findViewById(R.id.pb_sending);
              holder.errorIconImg = (ImageView) convertView
                      .findViewById(R.id.imageview_resending);
              holder.timeLengthTv = (TextView) convertView
                      .findViewById(R.id.tv_length);
              holder.unreadImg = (ImageView) convertView
                      .findViewById(R.id.iv_unread_voice);
          } else {
              convertView = mInflater.inflate(R.layout.row_received_voice, null);
              holder.timestampTv = (TextView) convertView
                      .findViewById(R.id.timestamp);
              holder.avatarImg = (ImageView) convertView
                      .findViewById(R.id.iv_userhead);
              holder.coverImg = (ImageView) convertView.findViewById(R.id.iv_voice);
              holder.pBar = (ProgressBar) convertView.findViewById(R.id.pb_receiving);
              holder.errorIconImg = (ImageView) convertView
                      .findViewById(R.id.imageview_rereceiving);
              holder.timeLengthTv = (TextView) convertView
                      .findViewById(R.id.tv_length);
              holder.unreadImg = (ImageView) convertView
                      .findViewById(R.id.iv_unread_voice);
          }
        break;
      }

      convertView.setTag(holder);
      mSArray.put(position, convertView);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    switch (sfyi.SFYType) {
    case TEXT:
      if (holder.speakLayout != null) {
        if (!sfyi.posterType.equals(PosterType.Turing)) {
          holder.speakLayout.setVisibility(View.GONE);

          int parentIconDefault = R.drawable.default_discussion_avatar;

          if (sfyi.posterType == PosterType.Parent) {
            parentIconDefault = R.drawable.default_useravatar;
            if (Tools.isNotEmpty(headIcon)) {
              Picasso.with(mContext)
                      .load(headIcon)
                      .placeholder(mContext.getResources().getDrawable(parentIconDefault))
                      .error(mContext.getResources().getDrawable(parentIconDefault))
                      .transform(new CircleTransform()).into(holder.avatarImg);
            } else if (Tools.isNotEmpty(ParentUri)) {
              Picasso
                      .with(mContext)
                      .load(ParentUri)
                      .placeholder(mContext.getResources().getDrawable(parentIconDefault))
                      .error(mContext.getResources().getDrawable(parentIconDefault))
                      .transform(new CircleTransform()).into(holder.avatarImg);
            }
          } else {
            if (Tools.isNotEmpty(headIcon)) {
              Picasso.with(mContext)
                      .load(headIcon)
                      .placeholder(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
                      .error(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
                      .transform(new CircleTransform()).into(holder.avatarImg);
            } else if (Tools.isNotEmpty(ParentUri)) {
              Picasso.with(mContext)
                      .load(ParentUri)
                      .placeholder(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
                      .error(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
                      .transform(new CircleTransform()).into(holder.avatarImg);
            }
          }
        }
      }
      break;
    case VIDEO:
      if (holder.speakLayout != null) {
        holder.speakLayout.setVisibility(View.VISIBLE);
      }
      if (Tools.isNotEmpty(sfyi.Src)) {
        Picasso.with(mContext).load(sfyi.Src).fit()
            .centerCrop().placeholder(mContext.getResources().getDrawable(R.drawable.default_cover))
            .error(mContext.getResources().getDrawable(R.drawable.default_cover))
            .into(holder.coverImg);
      }

      switch (sfyi.posterType) {
      case Parent:
        if (Tools.isNotEmpty(headIcon)) {
          Picasso.with(mContext).load(headIcon)
                  .placeholder(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
                  .error(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
                  .transform(new CircleTransform()).into(holder.avatarImg);
        } else  if (Tools.isNotEmpty(ParentUri)) {
          Picasso.with(mContext).load(ParentUri)
              .placeholder(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
              .error(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
              .transform(new CircleTransform()).into(holder.avatarImg);
        }
        break;
      case Turing:
        if (holder.avatarImg != null)
          holder.avatarImg.setImageResource(R.drawable.default_turning_avatar);
        break;
      default:
        break;
      }
      break;
    case VOICE:
      if (Tools.isNotEmpty(sfyi.length) && Tools.isNotEmpty(holder.timeLengthTv)) {
        if (sfyi.length == 0) {
          holder.timeLengthTv.setText(String.format("%s\"", sfyi.audio_length));
        } else {
          holder.timeLengthTv.setText(String.format("%s\"", sfyi.length));
        }
      }
      if (holder.unreadImg != null) {
        if (sfyi.hasRead == 1) {
          holder.unreadImg.setVisibility(View.GONE);
        } else {
          holder.unreadImg.setVisibility(View.VISIBLE);
        }
        if(sfyi.posterType == PosterType.Parent) { // to
          holder.coverImg.setOnClickListener(new VoicePlayClickListener(sfyi,
                  this, holder.errorIconImg, holder.coverImg, mContext, holder.pBar,
                  holder.unreadImg, true, mVoiceClickListener));
        } else { // from
          holder.coverImg.setOnClickListener(new VoicePlayClickListener(sfyi,
                  this, holder.errorIconImg, holder.coverImg, mContext, holder.pBar,
                  holder.unreadImg, false, mVoiceClickListener));
        }
      }

      switch (sfyi.posterType) {
        case Parent:
          if (Tools.isNotEmpty(headIcon)) {
            Picasso.with(mContext)
                    .load(headIcon)
                    .placeholder(mContext.getResources().getDrawable(R.drawable.default_useravatar))
                    .error(mContext.getResources().getDrawable(R.drawable.default_useravatar))
                    .transform(new CircleTransform()).into(holder.avatarImg);
          } else  if (Tools.isNotEmpty(ParentUri)) {
            Picasso
                    .with(mContext)
                    .load(ParentUri)
                    .placeholder(mContext.getResources().getDrawable(R.drawable.default_useravatar))
                    .error(mContext.getResources().getDrawable(R.drawable.default_useravatar))
                    .transform(new CircleTransform()).into(holder.avatarImg);
          }
          break;
        case Turing:
          if (holder.avatarImg != null)
            holder.avatarImg.setImageResource(R.drawable.default_turning_avatar);
          break;
        default:
          if (Tools.isNotEmpty(BabyUri)) {
            Picasso.with(mContext).load(BabyUri)
            .placeholder(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
            .error(mContext.getResources().getDrawable(R.drawable.default_discussion_avatar))
            .transform(new CircleTransform()).into(holder.avatarImg);
          }
          break;
      }
      break;
    default:
      break;
    }

    if (holder.contentTV != null) {
      holder.contentTV.setText(sfyi.Caption);
      holder.contentTV.setOnLongClickListener(new OnLongClickListener() {
        @SuppressWarnings("deprecation")
        @Override
        public boolean onLongClick(View v) {
          ClipboardManager cmb = (ClipboardManager) mContext
              .getSystemService(Context.CLIPBOARD_SERVICE);
          cmb.setText(sfyi.Caption);
          CommonUtil.showToask(mContext, "文字已复制到剪贴板~");
          return true;
        }
      });
    }

    holder.errorIconImg.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        EventBus.getDefault().post(new OnMediaResendEvent(sfyi));
      }
    });

    // Handle the state of sending messsage
    switch (sfyi.State) {
    case FAILED:
      holder.errorIconImg.setVisibility(View.VISIBLE);
      holder.pBar.setVisibility(View.GONE);
      break;
    case NONE:
      holder.errorIconImg.setVisibility(View.GONE);
      holder.pBar.setVisibility(View.GONE);
      break;
    case SUCCESS:
      holder.errorIconImg.setVisibility(View.GONE);
      holder.pBar.setVisibility(View.GONE);
      break;
    case SENDING:
      holder.pBar.setVisibility(View.VISIBLE);
      break;
    default:
      holder.errorIconImg.setVisibility(View.GONE);
      holder.pBar.setVisibility(View.GONE);
      break;
    }
    if (position == 0) {
      holder.timestampTv.setText(DateUtils.convert2ShortFormat(sfyi.createAt));
      holder.timestampTv.setVisibility(View.VISIBLE);
    } else {
      SpeakForYouItem lastSfyi = wordList.get(position - 1);
      if (DateUtils.isCloseEnough(sfyi.createAt, lastSfyi.createAt)) {
        holder.timestampTv.setVisibility(View.GONE);
      } else {
        holder.timestampTv.setText(DateUtils.convert2ShortFormat(sfyi.createAt));
        holder.timestampTv.setVisibility(View.VISIBLE);
      }
    }

    return convertView;
  }

  private class ViewHolder {
    TextView timestampTv;
    ImageView avatarImg;
    TextView contentTV;
    com.jdy.haoduoaiteacher.view.SquareLayout speakLayout;
    ImageView coverImg;
    ImageView errorIconImg;
    ProgressBar pBar;
    TextView timeLengthTv;
    ImageView unreadImg;
  }
}
